﻿
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.Reflection;

//using Raize.CodeSiteLogging;

namespace Pub
{
    public class CPub
    {
        public static Boolean B_Test = false;
        public static string exePath = "";
        public static string webPath = "";
        public static string sDebug = "";

        public CPub()
        {
        }

        /// <summary>
        /// 图片转换为字节
        /// </summary>
        /// <param name="byte1"></param>
        /// <returns></returns>
        public static Image btyeToImage(byte[] byte1)
        {
            MemoryStream ms = new MemoryStream(byte1);
            ms.Position = 0;
            Image img = Image.FromStream(ms);
            //ms.Close();
            return img;
        }

        /// <summary>
        /// 获得日期间隔
        /// </summary>
        /// <param name="s_dat"></param>
        /// <param name="e_dat"></param>
        /// <returns>XXX天XXX小时</returns>
        public static string DES_Time(object s_dat, object e_dat)
        {
            try
            {
                DateTime tim1 = to_DateTime(s_dat);
                DateTime tim2 = to_DateTime(e_dat);
                TimeSpan timspan = tim2 - tim1;
                double d1 = Math.Truncate(timspan.TotalDays);
                double d2 = timspan.TotalHours % 24;
                return d1.ToString() + " 天 " + (Math.Round(d2, 2)).ToString() + "小时";
            }
            catch (System.Exception ex)
            {
                Send(ex.ToString());
                return "";
            }
        }

        /// <summary>
        /// 判断结果集是否为空
        /// </summary>
        /// <param name="ds"></param>
        /// <returns></returns>
        public static Boolean dsIsNull(DataSet ds)
        {
            if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0) return true;
            else return false;
        }

        /// <summary>
        /// codesite 缩进
        /// </summary>
        /// <param name="sMsg"></param>
        public static void EnterMethod(string sMsg)
        {
            CDebug.EnterMethod(sMsg);
        }

        /// <summary>
        /// codesite 反缩进
        /// </summary>
        /// <param name="sMsg"></param>
        public static void ExitMethod(string sMsg)
        {
            CDebug.ExitMethod(sMsg);
        }

        public static void Send(DataSet ds)
        {
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                DataTable dt = ds.Tables[0];
                Send(dt);
            }
        }

        public static void Send(DataTable dt)
        {
            if (dt != null && dt.Rows.Count > 0)
            {
                String sCol = "";
                String sRow = "";

                foreach (DataColumn col in dt.Columns)
                {
                    sCol += col.Caption + "    ";
                }
                CDebug.Send(sCol);

                foreach (DataRow dr in dt.Rows)
                {
                    sRow = "";
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        sRow += dr[i].ToString() + "    ";
                    }
                    CDebug.Send(sRow);
                }
            }
        }

        /// <summary>
        /// DataSet填充ListView
        /// </summary>
        /// <param name="ds"></param>
        /// <param name="lv"></param>
        public static void Fill_lv(DataSet ds, ListView lv)
        {
            //填充listview
            lv.Columns.Clear();
            lv.Items.Clear();
            lv.View = View.Details;
            lv.FullRowSelect = true;
            lv.GridLines = true;

            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                DataTable table = new DataTable();
                table = ds.Tables[0];

                foreach (DataColumn col in table.Columns)
                {
                    ColumnHeader ch = new ColumnHeader();
                    ch.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
                    ch.Text = col.Caption;
                    ch.Width = 100;
                    lv.Columns.Add(ch);
                }

                foreach (DataRow dr in table.Rows)
                {
                    string[] str = new string[table.Columns.Count];
                    for (int i = 0; i < table.Columns.Count; i++)
                    {
                        str[i] = dr[i].ToString();
                    }
                    ListViewItem lst1 = new ListViewItem(str, 0);
                    lst1.ImageIndex = Convert.ToInt32(dr["桌台状态"]);
                    lv.Items.Add(lst1);
                }
                lv.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
            }
        }

        public static void Fill_lv2(DataSet ds, ListView lv)
        {
            //填充listview
            lv.Items.Clear();
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                lv.Columns.Clear();
                DataTable table = new DataTable();
                table = ds.Tables[0];

                foreach (DataColumn col in table.Columns)
                {
                    ColumnHeader ch = new ColumnHeader();
                    ch.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
                    ch.Text = col.Caption;
                    ch.Width = 100;
                    lv.Columns.Add(ch);
                }

                foreach (DataRow dr in table.Rows)
                {
                    string[] str = new string[table.Columns.Count];
                    for (int i = 0; i < table.Columns.Count; i++)
                    {
                        str[i] = dr[i].ToString();
                    }
                    ListViewItem lst1 = new ListViewItem(str, 0);
                    lv.Items.Add(lst1);
                }
                lv.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
            }
        }

        /// <summary>
        /// 查找关键字间的字符串
        /// </summary>
        /// <param name="str1"></param>
        /// <param name="strBegin"></param>
        /// <param name="strEnd"></param>
        /// <returns></returns>
        public static string findStrBetween(string str1, string strBegin, string strEnd)
        {
            //从第一个字符开始查找
            return findStrBetween(str1, 0, strBegin, strEnd);
        }

        /// <summary>
        /// 查找指定字符之间的字符串
        /// </summary>
        /// <param name="str1">原始字符串</param>
        /// <param name="i_Start">开始位置</param>
        /// <param name="strBegin">开始字符串</param>
        /// <param name="strEnd">结尾字符串</param>
        /// <returns></returns>
        public static string findStrBetween(string str1, int i_Start, string strBegin, string strEnd)
        {
            return findStrBetween(str1, i_Start, 0, strBegin, strEnd);
        }

        /// <summary>
        /// 查找指定字符之间的第n个字符串
        /// </summary>
        /// <param name="str1">原始字符串</param>
        /// <param name="i_Start">起始位置</param>
        /// <param name="i_Index">已找到字符串的Index</param>
        /// <param name="strBegin">开始字符</param>
        /// <param name="strEnd">结束字符</param>
        /// <returns>找到时返回找到值，没有找到是返回空字符串</returns>
        public static string findStrBetween(string str1, int i_Start, int i_Index, string strBegin, string strEnd)
        {
            //找到字符串的起始位置
            int i = i_Start;

            //如果开始字符为空，直接从指定开始位置算起
            if (strBegin != "" && strBegin != null)
            {
                for (int j = 0; j <= i_Index; j++)
                {
                    i = str1.IndexOf(strBegin, i);

                    //没有找到匹配项时直接返回空字符串
                    if (i == -1) return "";

                    i += strBegin.Length;
                }
            }

            //删除开始位置多余的字符串，只保留有用字符串
            str1 = str1.Substring(i, str1.Length - i);

            //如果结束字符为空，直接返回已找到字符串
            if (strEnd == "" || strEnd == null) return str1;

            //找到字符串的结束位置
            i = str1.IndexOf(strEnd);
            if (i == -1) return "";

            //截取找到的字符串
            str1 = str1.Substring(0, i);
            return str1;
        }

        /// <summary>
        /// 在指定字符串中按指定间隔，插入字符串
        /// </summary>
        /// <param name="str1">原始字符串</param>
        /// <param name="i_Step">长度间隔</param>
        /// <param name="s_Insert">待插入字符串</param>
        /// <returns>新字符串</returns>
        public static string insertStrStepN(string str1, int i_Step, string s_Insert)
        {
            string sResult = "";
            string sTem = str1;
            while (sTem.Length > i_Step)
            {
                string s1 = sTem.Substring(0, i_Step);
                sResult += s1 + s_Insert;
                sTem = sTem.Remove(0, i_Step);
            }
            if (sTem.Length > 0) sResult += sTem;
            return sResult;
        }


        /// <summary>
        /// 获得汉字字符串宽度
        /// </summary>
        /// <param name="s1"></param>
        /// <returns></returns>
        public static int getCnStrLength(string s1)
        {
            return Encoding.Default.GetByteCount(s1);
        }

        public static int getDsCount(DataSet ds)
        {
            if (dsIsNull(ds)) return 0;
            else return ds.Tables[0].Rows.Count;
        }

        /// <summary>
        /// 获取字符串MD5值
        /// </summary>
        /// <param name="sTxt"></param>
        /// <returns></returns>
        public static string getMD5(string sTxt)
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sTxt, "MD5");
        }

        public static string getMD5(string sTxt, int iTyp)
        {
            string sMD5 = "";

            if (iTyp == 1)
            {
                //获取加密服务  
                System.Security.Cryptography.MD5CryptoServiceProvider md5CSP = new System.Security.Cryptography.MD5CryptoServiceProvider();

                //获取要加密的字段，并转化为Byte[]数组  
                byte[] testEncrypt = System.Text.Encoding.Unicode.GetBytes(sTxt);

                //加密Byte[]数组  
                byte[] resultEncrypt = md5CSP.ComputeHash(testEncrypt);

                //将加密后的数组转化为字段(普通加密)  
                //sMD5 = System.Text.Encoding.Unicode.GetString(resultEncrypt);
                sMD5 = bytes_to_str(resultEncrypt);
            }
            else
            {
                //作为密码方式加密   
                sMD5 = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sTxt, "MD5");
            }
            return sMD5;
        }

        /// <summary>
        /// 字节数组MD5计算
        /// </summary>
        /// <param name="testEncrypt"></param>
        /// <returns></returns>
        public static string getMD5(byte[] testEncrypt)
        {
            //获取加密服务  
            System.Security.Cryptography.MD5CryptoServiceProvider md5CSP = new System.Security.Cryptography.MD5CryptoServiceProvider();

            //加密Byte[]数组  
            byte[] resultEncrypt = md5CSP.ComputeHash(testEncrypt);

            //将加密后的数组转化为字段(普通加密)  
            //sMD5 = System.Text.Encoding.Unicode.GetString(resultEncrypt);
            return bytes_to_str(resultEncrypt);
        }

        /// <summary>
        /// 获取sha1字符串
        /// </summary>
        /// <param name="sTxt"></param>
        /// <returns></returns>
        public static string getSHA1(string sTxt)
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sTxt, "SHA1");
        }

        /// <summary>
        /// 弹出MessageBox,带返回值True/False
        /// </summary>
        /// <param name="s_msg"></param>
        /// <param name="s_tit"></param>
        /// <returns></returns>
        public static Boolean MsgBox(string s_msg, string s_tit)
        {
            MessageBoxButtons btn = MessageBoxButtons.YesNo;
            MessageBoxIcon ico = MessageBoxIcon.Question;
            DialogResult rst = DialogResult.Yes;
            if (MessageBox.Show(s_msg, s_tit, btn, ico) == rst) return true;
            else return false;
        }

        public static void MsgBox(string s_msg)
        {
            MessageBox.Show(s_msg);
        }

        public static Boolean MsgBox(string s_msg, string s_tit, MessageBoxIcon ico)
        {
            MessageBoxButtons btn = MessageBoxButtons.YesNo;
            DialogResult rst = DialogResult.Yes;
            if (MessageBox.Show(s_msg, s_tit, btn, ico) == rst) return true;
            else return false;
        }

        /// <summary>
        /// 运行外部程序
        /// </summary>
        /// <param name="exeNam"></param>
        /// <param name="parm"></param>
        public static void runExe(string exeNam, string parm)
        {
            //声明一个程序信息类
            System.Diagnostics.ProcessStartInfo Info = new System.Diagnostics.ProcessStartInfo();

            //设置外部程序名
            //Info.FileName = "notepad.exe";
            Info.FileName = exeNam;

            //设置外部程序的启动参数（命令行参数）为test.txt
            //Info.Arguments = "test.txt";
            Info.Arguments = parm;

            //设置外部程序工作目录为  C:\
            Info.WorkingDirectory = "C:\\";

            //声明一个程序类
            System.Diagnostics.Process Proc;

            try
            {
                //
                //启动外部程序
                //
                Proc = System.Diagnostics.Process.Start(Info);
            }
            catch (System.ComponentModel.Win32Exception e)
            {
                Console.WriteLine("系统找不到指定的程序文件。\r{0}", e);
                return;
            }

            //打印出外部程序的开始执行时间
            Console.WriteLine("外部程序的开始执行时间：{0}", Proc.StartTime);

            /*
            return;
            //等待3秒钟
            Proc.WaitForExit(3000);

            //如果这个外部程序没有结束运行则对其强行终止
            if (Proc.HasExited == false)
            {
                Console.WriteLine("由主程序强行终止外部程序的运行！");
                Proc.Kill();
            }
            else
            {
                Console.WriteLine("由外部程序正常退出！");
            }
            Console.WriteLine("外部程序的结束运行时间：{0}", Proc.ExitTime);
            Console.WriteLine("外部程序在结束运行时的返回值：{0}", Proc.ExitCode);
             * */
        }

        /// <summary>
        /// 输出调试信息
        /// </summary>
        /// <param name="sMsg"></param>
        public static void Send(string sMsg)
        {
            /*
            CodeSiteDestination dest = new CodeSiteDestination();
            dest.LogFile.Active = true;
            dest.LogFile.FileName = "MyFirstLog.csl";
            //dest.LogFile.FilePath = "$(MyDocs)";
            dest.LogFile.FilePath = Path.GetDirectoryName(Application.ExecutablePath);
            dest.Viewer.Active = true;
            CodeSite.Destination = dest;
            */
            CDebug.Send(sMsg);
            Debug.WriteLine("___" + sNow() + "_________________________________________________________");
            Debug.WriteLine(sMsg);
        }

        /// <summary>
        /// 输出调试信息
        /// </summary>
        /// <param name="sMsg"></param>
        /// <param name="sObj"></param>
        public static void Send(string sMsg, object sObj)
        {
            CDebug.Send(sMsg, sObj);
        }

        /// <summary>
        /// 输出调试信息
        /// </summary>
        /// <param name="sMsg"></param>
        /// <param name="sObj"></param>
        public static void Send(object sObj)
        {
            CDebug.Send(sNow(), sObj);
        }

        /// <summary>
        /// 设置窗体父容器
        /// </summary>
        /// <param name="f1"></param>
        /// <param name="c1"></param>
        public static void SetParentI(Form f1, Control c1)
        {
            f1.TopLevel = false;
            f1.FormBorderStyle = FormBorderStyle.None;
            f1.Parent = c1;
            f1.Dock = DockStyle.Fill;
            f1.Show();
        }

        /// <summary>
        /// 当前日期字符串
        /// </summary>
        /// <returns>yyyy-MM-dd HH:mm:ss</returns>
        public static string sNow()
        {
            return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }

        public static string sNow(string sDateTimeFormat)
        {
            return DateTime.Now.ToString(sDateTimeFormat);
        }
        /// <summary>
        /// string数组 冒泡排序 由小到大
        /// </summary>
        /// <param name="flist"></param>
        public static void taxis(string[] flist)
        {
            for (int i = flist.Length - 1; i > 0; i--)
            {
                for (int k = i - 1; k >= 0; k--)
                {
                    if (string.Compare(flist[i], flist[k]) < 0)
                    {
                        string s_tem = flist[i];
                        flist[i] = flist[k];
                        flist[k] = s_tem;
                    }
                }
            }
        }

        /// <summary>
        /// string数组 冒泡排序 由大到小
        /// </summary>
        /// <param name="flist"></param>
        public static void taxisDesc(string[] flist)
        {
            for (int i = flist.Length - 1; i > 0; i--)
            {
                for (int k = i - 1; k >= 0; k--)
                {
                    if (string.Compare(flist[i], flist[k]) > 0)
                    {
                        string s_tem = flist[i];
                        flist[i] = flist[k];
                        flist[k] = s_tem;
                    }
                }
            }
        }

        public static DateTime to_DateTime(object obj1)
        {
            try
            {
                if (obj1 == null) return Convert.ToDateTime("2000-1-1");
                else return Convert.ToDateTime(obj1);
            }
            catch (System.Exception ex)
            {
                Send(ex.ToString());
                return Convert.ToDateTime("2000-1-1");
            }
        }

        public static Double to_Double(object obj1)
        {
            try
            {
                if (obj1 == null) return 0;
                else return Convert.ToDouble(obj1);
            }
            catch
            {
                return 0;
            }
        }

        public static int to_int(object obj1)
        {
            try
            {
                if (obj1 == null) return 0;
                else return Convert.ToInt32(obj1);
            }
            catch
            {
                return 0;
            }
        }

        public static string to_String(object obj1)
        {
            try
            {
                if (obj1 == null) return "";
                else return Convert.ToString(obj1).Trim();
            }
            catch (System.Exception ex)
            {
                CPub.Send(ex.ToString());
                return "";
            }
        }

        
        /// <summary>
        /// 在指定字符串的前后， 插入特定字符
        /// </summary>
        /// <param name="str1">原始字符串</param>
        /// <param name="i_Typ">0 - 表示前，  1-表示后</param>
        /// <param name="s_Insert">待插入字符</param>
        /// <param name="s_TotlePos">插入后字符串总长度</param>
        /// <returns>新字符串</returns>
        public static string insertStrChr(string str1, int i_Typ, string s_Insert, int s_TotlePos)
        {
            string sResult = "";
            string ChrStr = "";
            string sTem = str1.Trim();
            for (int i = 0; i < s_TotlePos - sTem.Length; i++) { ChrStr += s_Insert; }
            if (i_Typ == 0) { sResult = ChrStr + sTem; }
            if (i_Typ == 1) { sResult = sTem + ChrStr; }
            return sResult;
        }

        /// <summary>
        /// 16进制字符串转换成byte数组
        /// </summary>
        /// <param name="sTxt"></param>
        /// <returns></returns>
        public static byte[] str_to_bytes(string sTxt)
        {
            byte[] b1;
            string sTemp = sTxt;
            while (sTemp.IndexOf("\r") != -1) sTemp = sTemp.Replace("\r", "");
            while (sTemp.IndexOf("\n") != -1) sTemp = sTemp.Replace("\n", "");
            while (sTemp.IndexOf(" ") != -1) sTemp = sTemp.Replace(" ", "");
            sTemp = insertStrStepN(sTemp, 2, " ");
            string[] sArray = sTemp.Split(' ');
            b1 = new byte[sArray.Length];
            for (int i = 0; i < sArray.Length; i++)
            {
                b1[i] = Convert.ToByte(int.Parse(sArray[i], System.Globalization.NumberStyles.AllowHexSpecifier));
            }
            return b1;
        }

        /// <summary>
        /// byte数组转换为16进制数据字符串
        /// </summary>
        /// <param name="bDat"></param>
        /// <returns></returns>
        public static string bytes_to_str(byte[] bDat)
        {
            if (bDat == null) return "";
            string s1 = "";
            for (int i = 0; i < bDat.Length; i++)
            {
                string sTemp = Convert.ToInt16(bDat[i]).ToString("X");
                if (sTemp.Length == 1) sTemp = "0" + sTemp;
                s1 += sTemp;
            }
            return s1;
        }

        /// <summary>
        ///  byte数组转换为16进制数据字符串
        /// </summary>
        /// <param name="bDat">byte数组</param>
        /// <param name="strSplit">插入分隔符</param>
        /// <returns></returns>
        public static string bytes_to_str(byte[] bDat, string strSplit)
        {
            string sTxt = bytes_to_str(bDat);
            sTxt = insertStrStepN(sTxt, 2, strSplit);
            return sTxt;
        }

        /// <summary>
        /// byte数组转换为16进制数据字符串
        /// </summary>
        /// <param name="bDat">byte数组</param>
        /// <param name="strSplit">插入分隔符</param>
        /// <param name="iR_N_">换行长度</param>
        /// <returns></returns>
        public static string bytes_to_str(byte[] bDat, string strSplit, int iR_N_)
        {
            string sTxt = bytes_to_str(bDat, strSplit);
            if (iR_N_ > 0) sTxt = insertStrStepN(sTxt, iR_N_, "\r\n");
            return sTxt;
        }

        /// <summary>
        /// 十六进制转十进制
        /// </summary>
        /// <param name="sHex"></param>
        /// <returns></returns>
        public static string HexToDec(string sHex)
        {
            string sTem = sHex;
            sTem = sTem.Replace("\r", "");
            sTem = sTem.Replace("\n", "");
            sTem = sTem.Replace(" ", "");
            return int.Parse(sTem, System.Globalization.NumberStyles.AllowHexSpecifier).ToString();
        }

        /// <summary>
        /// 十六进制字符串数组转十进制数据
        /// </summary>
        /// <param name="sHex">字符串</param>
        /// <param name="sSplit">数组分隔符</param>
        /// <returns></returns>
        public static string HexToDec(string sHex, char sSplit)
        {
            return HexToDec(sHex, sSplit, sSplit);
        }

        public static string HexToDec(string sHex, char sSplit, char sSplit_Out)
        {
            string sTem = "";
            string[] sAry = sHex.Split(sSplit);
            for (int i = 0; i < sAry.Length; i++)
            {
                if (i != 0) sTem += sSplit_Out.ToString();
                if (sAry[i] != "") sTem += HexToDec(sAry[i]);
            }
            return sTem;
        }

        /// <summary>
        /// 十进制转十六进制
        /// </summary>
        /// <param name="sDec"></param>
        /// <returns></returns>
        public static string DecToHex(string sDec)
        {
            return Convert.ToInt64(sDec).ToString("X");
        }

        /// <summary>
        /// 十进制数组转十六进制
        /// </summary>
        /// <param name="sDec"></param>
        /// <returns></returns>
        public static string DecToHex(string[] sDec)
        {
            string sTem = "";
            for (int i = 0; i < sDec.Length;i++ )
            {
                sTem += DecToHex(sDec[i]); 
            }
            return sTem;
        }

        /// <summary>
        /// IP转十六进制
        /// </summary>
        /// <param name="sIP"></param>
        /// <returns></returns>
        public static string IP_to_Hex(string sIP)
        {
            string sTem = "";
            string[] sAry = sIP.Split('.');
            sTem = DecToHex(sAry);
            return sTem;
        }

        /// <summary>
        /// 十六进制转IP
        /// </summary>
        /// <param name="sHex"></param>
        /// <returns></returns>
        public static string Hex_to_IP(string sHex)
        {
            string sTem = "";
            string s1 = CPub.insertStrStepN(sHex.Replace(" ", ""), 2, " ");
            sTem = HexToDec(s1, ' ', '.');
            return sTem;
        }

        /// <summary>
        /// DateTime转UTC
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static double DateTime_to_Int(System.DateTime time)
        {
            double intResult = 0;
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            intResult = (time - startTime).TotalSeconds;
            return intResult;
        }

        /// <summary>
        /// UTC转DateTime
        /// </summary>
        /// <param name="utc"></param>
        /// <returns></returns>
        public static DateTime Int_to_DateTime(double utc)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            startTime = startTime.AddSeconds(utc);
            //startTime = startTime.AddHours(8);//转化为北京时间(北京时间=UTC时间+8小时 )
            return startTime;
        }

        /// <summary>
        /// 十六进制转日期
        /// </summary>
        /// <param name="sHex"></param>
        /// <returns></returns>
        public static string Hex_to_DateTime(string sHex)
        {
            string sTem = "";
            double d1 = Convert.ToDouble(HexToDec(sHex));
            DateTime dat1 = Int_to_DateTime(d1);
            sTem = dat1.ToString("yyyy-MM-dd HH:mm:ss");
            return sTem;
        }

        /// <summary>
        /// 日期转十六进制
        /// </summary>
        /// <param name="sDat"></param>
        /// <returns></returns>
        public static string DateTime_to_Hex(string sDat)
        {
            string sTime;
            DateTime dat1 = Convert.ToDateTime(sDat);
            double d1 = DateTime_to_Int(dat1);
            sTime = DecToHex(d1.ToString());
            return sTime;
        }

        /// <summary>
        /// 反转十六进制字符串 AA BB CC DD 转为 DD CC BB AA 输入字符串可以不包含空格分隔
        /// </summary>
        /// <param name="sHex"></param>
        /// <returns></returns>
        public static string HexReversal(string sHex)
        {
            sHex = sHex.Replace(" ", "");           //删除空格
            sHex = insertStrStepN(sHex, 2, " ");    //插入空格
            string[] s1 = sHex.Split(' ');
            string s2 = "";
            for (int i = 0; i < s1.Length; i++) s2 = s1[i] + s2;
            return s2;
        }

        /// <summary>
        /// 结构体转byte数组
        /// </summary>
        /// <param name="structObj">要转换的结构体</param>
        /// <returns>转换后的byte数组</returns>
        public static byte[] StructToBytes(object structObj)
        {
            //得到结构体的大小
            int size = Marshal.SizeOf(structObj);
            //创建byte数组
            byte[] bytes = new byte[size];
            //分配结构体大小的内存空间
            IntPtr structPtr = Marshal.AllocHGlobal(size);
            //将结构体拷到分配好的内存空间
            Marshal.StructureToPtr(structObj, structPtr, false);
            //从内存空间拷到byte数组
            Marshal.Copy(structPtr, bytes, 0, size);
            //释放内存空间
            Marshal.FreeHGlobal(structPtr);
            //返回byte数组
            return bytes;
        }

        /// <summary>
        /// byte数组转结构体
        /// </summary>
        /// <param name="bytes">byte数组</param>
        /// <param name="type">结构体类型</param>
        /// <returns>转换后的结构体</returns>
        public static void BytesToStuct(byte[] bytes, object type1)
        {
            BytesToStuct(bytes, type1, 0);
        }

        /// <summary>
        /// byte[] 转结构体
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="type1"></param>
        /// <param name="startIndex">偏移</param>
        public static void BytesToStuct(byte[] bytes, object type1, Int32 startIndex)
        {
            //得到结构体的大小
            int size = Marshal.SizeOf(type1);
            //byte数组长度小于结构体的大小
            if (size > bytes.Length)
            {
                //返回空
                return;
            }
            //分配结构体大小的内存空间
            IntPtr structPtr = Marshal.AllocHGlobal(size);
            //将byte数组拷到分配好的内存空间
            Marshal.Copy(bytes, startIndex, structPtr, size);
            //将内存空间转换为目标结构体
            Marshal.PtrToStructure(structPtr, type1);
            //释放内存空间
            Marshal.FreeHGlobal(structPtr);
        }

        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="obj1"></param>
        /// <param name="fileName"></param>
        public static void Serialize(object obj1, string fileName)
        {
            try
            {
                //创建二进制文件temp.dat
                FileStream fileStream = new FileStream(fileName, FileMode.Create);
                BinaryFormatter b = new BinaryFormatter();

                //将Student实例对象序列化给fileStream流：其含义是这时候的Student对象已经存储到temp.dat 文件中
                b.Serialize(fileStream, obj1);
                fileStream.Flush();
                fileStream.Close();
                fileStream.Dispose();
            }
            catch (System.Exception ex)
            {
                CDebug.SendError(ex.ToString());
            }
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static Object Deserialize(string fileName)
        {
            Object obj1 = new Object();
            try
            {
                FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                //BinaryFormatter b = new BinaryFormatter();
                //将temp.dat 的文件流反序列化为Student
                //obj1 = b.Deserialize(fileStream);

                IFormatter formatter = new BinaryFormatter();
                formatter.Binder = new UBinder();
                obj1 = (Object)formatter.Deserialize(fileStream);
                //释放文件流资源
                fileStream.Flush();
                fileStream.Close();
                fileStream.Dispose();
            }
            catch (System.Exception ex)
            {
                CDebug.SendError(ex.ToString());
            }
            return obj1;
        }
    }

    public class UBinder : SerializationBinder
    {
        public override Type BindToType(string assemblyName, string typeName)
        {
            Assembly ass = Assembly.GetExecutingAssembly();
            return ass.GetType(typeName);
        }
    }
}